package com.gz.controller;

import com.gz.entity.Book;
import com.gz.entity.Vo.CartItemVo;
import com.gz.entity.Vo.CartVo;
import com.gz.exception.SystemCode;
import com.gz.service.CartService;
import com.gz.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/cart")
//@Api(tags = "购物车接口")
@Slf4j
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private JwtUtil jwtUtil;  //要实现会话跟踪，从Token中获取用户id

    /**
     * 查询购物车
     */
    @PostMapping("/getCartList/{id}")
//    @ApiOperation("查询购物车")
    public ResponseEntity<CartVo> getCartList(@PathVariable Long id) {
        //调用业务层查询购物车
        CartVo cart = cartService.getCart(id);
        log.info("购物车信息:{}", cart);
        return ResponseEntity.ok(cart);
    }

    @PostMapping("/addToCart/{id}")
    public ResponseEntity addToCart(@PathVariable Long id, @RequestBody Book book) {
        CartItemVo cartItemVo=new CartItemVo();
        cartItemVo.setQuantity(1);
        cartItemVo.setName(book.getName());
        cartItemVo.setPrice(book.getPrice());
        cartItemVo.setUserId(id);
        cartItemVo.setBookId(book.getId());
        cartItemVo.setImage(book.getImgSrc());
        cartItemVo.setSum(cartItemVo.getPriceToQuantitySum());
        cartService.addCartItem(cartItemVo);
        return ResponseEntity.ok(SystemCode.SUCCESS_CART.getMessage());
    }

    @PostMapping("/updateCart/{bookId}/{quantity}/{id}")
    public ResponseEntity updateCart(@PathVariable Long bookId, @PathVariable Integer quantity, @PathVariable Long id) {
        cartService.updateCart(bookId,quantity,id);
        return ResponseEntity.ok(SystemCode.SUCCESS_CART_UPDATE.getMessage());
    }

    @DeleteMapping("/deleteCartItem/{bookId}/{id}")
    public ResponseEntity deleteCartItem(@PathVariable Long bookId, @PathVariable Long id) {
        cartService.deleteCartItem(bookId,id);
        return ResponseEntity.ok(SystemCode.SUCCESS_CART_DELETE_ITEM.getMessage());
    }

    @DeleteMapping("/clearCart/{id}")
    public ResponseEntity clearCart(@PathVariable Long id) {
        cartService.clearCart(id);
        return ResponseEntity.ok(SystemCode.SUCCESS_CLEAR_CART.getMessage());
    }

}